<template>
  <div class="app-container">
    <!-- 搜索和操作工具栏 -->
    <el-card class="search-action-card" shadow="never">
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
        label-width="100px"
        class="search-form"
      >
        <el-form-item label="企业信息" prop="companyName">
          <el-input
            v-model="queryParams.companyName"
            placeholder="请输入企业名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="委托开始时间" prop="entrustStartDate">
          <el-date-picker
            v-model="queryParams.entrustStartDate"
            type="month"
            placeholder="请选择委托开始时间"
            value-format="YYYY-MM"
            style="width: 150px"
            clearable
          />
        </el-form-item>

        <el-form-item label="委托结束时间" prop="entrustEndDate">
          <el-date-picker
            v-model="queryParams.entrustEndDate"
            type="month"
            placeholder="请选择委托结束时间"
            value-format="YYYY-MM"
            style="width: 150px"
            clearable
          />
        </el-form-item>

        <el-form-item label="开票状态" prop="invoiceStatus">
          <el-select v-model="queryParams.invoiceStatus" placeholder="请选择开票状态" clearable style="width: 150px">
            <el-option label="未开票" value="0" />
            <el-option label="已开票" value="1" />
          </el-select>
        </el-form-item>
        
        <el-form-item class="search-buttons">
          <el-button type="primary" @click="handleQuery" :icon="Search">搜索</el-button>
          <el-button @click="resetQuery" :icon="Refresh">重置</el-button>
        </el-form-item>

        <el-form-item class="action-buttons">
          <el-button
            type="primary"
            :icon="Plus"
            @click="openGenerateDialog"
            v-hasPermi="['oa:enterprise-bill-summary:create']"
          >
            账单生成
          </el-button>
          <el-button
            type="success"
            :icon="Check"
            :disabled="!selectedIds.length"
            @click="handleBatchInvoice"
            v-hasPermi="['oa:enterprise-bill-summary:update']"
          >
            一键开票
          </el-button>
          <el-button
            type="warning"
            :icon="Download"
            @click="handleExport"
            :loading="exportLoading"
            :disabled="exportLoading"
            v-hasPermi="['oa:enterprise-bill-summary:export']"
          >
            {{ exportLoading ? '导出中...' : '导出' }}
          </el-button>
        </el-form-item>

        <el-form-item>
          <span class="selected-count" v-if="selectedIds.length > 0">
            已选择 {{ selectedIds.length }} 项
          </span>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
        stripe
        border
        class="data-table"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="企业信息" align="center" prop="companyName" min-width="150">
          <template #default="scope">
            {{ scope.row.companyName }}
          </template>
        </el-table-column>
        <el-table-column label="委托开始时间" align="center" prop="entrustStartDate" width="130">
          <template #default="scope">
            <span class="time-text">{{ scope.row.entrustStartDate || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="委托结束时间" align="center" prop="entrustEndDate" width="130">
          <template #default="scope">
            <span class="time-text">{{ scope.row.entrustEndDate || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="服务时长(月)" align="center" prop="serviceDurationMonths" width="110">
          <template #default="scope">
            <el-tag type="info" size="small">{{ scope.row.serviceDurationMonths }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="收费总金额" align="center" prop="totalAmount" width="130">
          <template #default="scope">
            <span class="amount-text">{{ formatMoney(scope.row.totalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开票状态" align="center" prop="invoiceStatus" width="100">
          <template #default="scope">
            <el-tag 
              :type="scope.row.invoiceStatus === '0' ? 'warning' : 'success'" 
              size="small"
              @click="handleViewInvoiceStatus(scope.row)"
              class="status-tag"
            >
              {{ scope.row.invoiceStatus === '0' ? '未开票' : '已开票' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开票信息" align="center" prop="invoiceInfoDetail" width="100">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              size="small"
              @click="handleViewInvoiceInfo(scope.row)"
            >
              {{'查看详情' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="收款信息" align="center" prop="collectionInfoDetail" width="100">
          <template #default="scope">
            <el-button 
              type="primary" 
              link 
              size="small"
              @click="handleViewCollectionInfo(scope.row)"
            >
              {{'查看详情' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              v-hasPermi="['oa:enterprise-bill-summary:update']"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
              v-hasPermi="['oa:enterprise-bill-summary:delete']"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <Pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 账单生成对话框 -->
    <el-dialog
      v-model="generateDialogVisible"
      title="账单生成"
      width="500px"
      append-to-body
      :close-on-click-modal="!generateLoading"
      :close-on-press-escape="!generateLoading"
      :show-close="!generateLoading"
    >
      <el-form
        ref="generateFormRef"
        :model="generateForm"
        :rules="generateRules"
        label-width="120px"
      >
        <!-- <el-form-item label="选择企业" prop="companyIds">
          <el-select
            v-model="generateForm.companyIds"
            multiple
            filterable
            placeholder="请选择企业，不选代表生成所有企业数据"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="company in companyOptions"
              :key="company.id"
              :label="company.companyName"
              :value="company.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="账单开始时间" prop="billStartDate">
          <el-date-picker
            v-model="generateForm.billStartDate"
            type="month"
            placeholder="请选择账单开始时间"
            value-format="YYYY-MM"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="账单结束时间" prop="billEndDate">
          <el-date-picker
            v-model="generateForm.billEndDate"
            type="month"
            placeholder="请选择账单结束时间"
            value-format="YYYY-MM"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button 
            type="primary" 
            @click="handleGenerate" 
            :loading="generateLoading"
            :disabled="generateLoading"
          >
            {{ generateLoading ? '生成中...' : '确 定' }}
          </el-button>
          <el-button 
            @click="generateDialogVisible = false"
            :disabled="generateLoading"
          >
            取 消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 开票信息详情对话框 -->
    <el-dialog
      v-model="invoiceInfoDialogVisible"
      title="开票信息详情"
      width="700px"
      append-to-body
    >
      <div v-if="currentInvoiceInfo" class="info-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="开票名称">{{ currentInvoiceInfo.invoiceName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="纳税识别号">{{ currentInvoiceInfo.taxNumber || '-' }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ currentInvoiceInfo.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ currentInvoiceInfo.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="开户银行名称">{{ currentInvoiceInfo.bankName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="开户银行账号">{{ currentInvoiceInfo.bankAccount || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else class="no-data">
        <el-empty description="暂无开票信息" />
      </div>
    </el-dialog>

    <!-- 收款信息详情对话框 -->
    <el-dialog
      v-model="collectionInfoDialogVisible"
      title="收款信息详情"
      width="700px"
      append-to-body
    >
      <div v-if="currentCollectionInfo" class="info-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="开票名称">{{ currentCollectionInfo.invoiceName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="纳税识别号">{{ currentCollectionInfo.taxNumber || '-' }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ currentCollectionInfo.address || '-' }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ currentCollectionInfo.phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="开户银行名称">{{ currentCollectionInfo.bankName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="开户银行账号">{{ currentCollectionInfo.bankAccount || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else class="no-data">
        <el-empty description="暂无收款信息" />
      </div>
    </el-dialog>

    <!-- 编辑表单组件 -->
    <EnterpriseBillSummaryForm
      ref="formRef"
      @success="handleFormSuccess"
      @close="handleFormClose"
    />
  </div>
</template>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-action-card {
  margin-bottom: 16px;
  border-radius: 8px;
}

.search-form {
  padding: 8px 0;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.search-form .el-form-item {
  margin-bottom: 8px;
  margin-right: 16px;
}

.search-buttons {
  margin-right: 24px !important;
}

.action-buttons {
  margin-right: 24px !important;
}

.action-buttons .el-button {
  margin-right: 8px;
}

.selected-count {
  color: #409eff;
  font-size: 14px;
  font-weight: 500;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border-radius: 4px;
  border: 1px solid #b3d8ff;
}

.table-card {
  border-radius: 8px;
}

.data-table {
  border-radius: 8px;
  overflow: hidden;
}

.company-link {
  font-weight: 500;
  text-decoration: none;
}

.company-link:hover {
  text-decoration: underline;
}

.time-text {
  color: #606266;
  font-size: 13px;
}

.amount-text {
  color: #e6a23c;
  font-weight: 600;
  font-size: 14px;
}

.status-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.status-tag:hover {
  transform: scale(1.05);
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-button--link) {
  padding: 4px 8px;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-card) {
  border: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 16px 20px;
}

.info-detail {
  padding: 16px 0;
}

.no-data {
  padding: 40px 0;
  text-align: center;
}
</style>

<script setup lang="ts" name="EnterpriseBillSummary">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { Search, Refresh, Plus, Check, Download } from '@element-plus/icons-vue'
import { getEnterpriseBillSummaryPageApi, deleteEnterpriseBillSummaryApi, generateEnterpriseBillSummaryApi, updateInvoiceStatusApi, exportEnterpriseBillSummaryApi, getInvoiceInfoApi, getCollectionInfoApi } from '@/api/oa/enterprisebillsummary'
import { AccountingCompaniesApi } from '@/api/oa/accountingcompanies'
import type { EnterpriseBillSummaryVO, EnterpriseBillSummaryPageReqVO, EnterpriseBillSummaryGenerateReqVO, AccountingCompaniesInvoiceVO } from '@/api/oa/enterprisebillsummary'
import EnterpriseBillSummaryForm from './EnterpriseBillSummaryForm.vue'
import download from '@/utils/download'

const message = useMessage() // 消息弹窗

// 权限指令
const vHasPermi = {
  mounted(el: any, binding: any) {
    // 这里可以添加权限检查逻辑
    // 暂时跳过权限检查
  }
}

defineOptions({ name: 'EnterpriseBillSummary' })

const loading = ref(false)
const total = ref(0)
const list = ref<EnterpriseBillSummaryVO[]>([])
const selectedIds = ref<number[]>([])
const companyOptions = ref<any[]>([])

// 查询参数
const queryParams = reactive<EnterpriseBillSummaryPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  companyName: undefined,
  entrustStartDate: undefined,
  entrustEndDate: undefined,
  invoiceStatus: undefined
})

// 账单生成表单
const generateForm = reactive<EnterpriseBillSummaryGenerateReqVO>({
  companyIds: [],
  billStartDate: '',
  billEndDate: ''
})

const generateRules = {
  billStartDate: [{ required: true, message: '账单开始时间不能为空', trigger: 'blur' }],
  billEndDate: [{ required: true, message: '账单结束时间不能为空', trigger: 'blur' }]
}

// 对话框显示状态
const generateDialogVisible = ref(false)
const invoiceInfoDialogVisible = ref(false)
const collectionInfoDialogVisible = ref(false)

// 当前查看的信息
const currentInvoiceInfo = ref<AccountingCompaniesInvoiceVO | null>(null)
const currentCollectionInfo = ref<AccountingCompaniesInvoiceVO | null>(null)

// 表单引用
const queryFormRef = ref()
const generateFormRef = ref()
const formRef = ref<InstanceType<typeof EnterpriseBillSummaryForm>>()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getEnterpriseBillSummaryPageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.companyName = undefined
  queryParams.entrustStartDate = undefined
  queryParams.entrustEndDate = undefined
  queryParams.invoiceStatus = undefined
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: EnterpriseBillSummaryVO[]) => {
  selectedIds.value = selection.map(item => item.id)
}

/** 加载企业选项 */
const loadCompanyOptions = async () => {
  // try {
  //   const data = await AccountingCompaniesApi.getAllValidCompanies()
  //   companyOptions.value = data.map((company: any) => ({
  //     id: company.id,
  //     companyName: company.companyName
  //   }))
  // } catch (error) {
  //   console.error('加载企业列表失败:', error)
  //   ElMessage.error('加载企业列表失败')
  // }
}

/** 打开账单生成对话框 */
const openGenerateDialog = async () => {
  generateDialogVisible.value = true
  // 加载企业列表
  await loadCompanyOptions()
}

// 账单生成加载状态
const generateLoading = ref(false)

/** 生成账单 */
const handleGenerate = async () => {
  const valid = await generateFormRef.value?.validate()
  if (!valid) return

  generateLoading.value = true
  
  // 显示全屏加载
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在生成账单，请稍候...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const batchNo = await generateEnterpriseBillSummaryApi(generateForm)
    
    ElMessage.success(`账单生成成功，批次号：${batchNo}`)
    generateDialogVisible.value = false
    // 重置表单
    generateForm.companyIds = []
    generateForm.billStartDate = ''
    generateForm.billEndDate = ''
    getList()
  } catch (error) {
    console.error('生成账单失败:', error)
    ElMessage.error('账单生成失败，请重试')
  } finally {
    // 关闭加载
    loadingInstance.close()
    generateLoading.value = false
  }
}

/** 批量开票 */
const handleBatchInvoice = async () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请选择要开票的记录')
    return
  }

  try {
    await ElMessageBox.confirm('确认将选中的记录标记为已开票吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await updateInvoiceStatusApi(selectedIds.value, '1')
    ElMessage.success('开票状态更新成功')
    getList()
  } catch (error) {
    console.error('更新开票状态失败:', error)
  }
}

// 导出加载状态
const exportLoading = ref(false)

/** 导出 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    console.log('开始导出，查询参数:', queryParams)
    const data = await exportEnterpriseBillSummaryApi(queryParams)
    console.log('导出数据:', data)
    console.log('数据类型:', typeof data)
    download.excel(data, '企业账单汇总.xls')
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

/** 编辑 */
const handleEdit = (row: EnterpriseBillSummaryVO) => {
  if (formRef.value) {
    formRef.value.open(row)
  }
}

/** 表单提交成功 */
const handleFormSuccess = () => {
  getList()
}

/** 表单关闭 */
const handleFormClose = () => {
  // 可以在这里添加关闭时的逻辑
}

/** 删除 */
const handleDelete = async (row: EnterpriseBillSummaryVO) => {
  try {
    await ElMessageBox.confirm('确认删除该记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteEnterpriseBillSummaryApi(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

/** 查看企业详情 */
const handleViewCompany = (row: EnterpriseBillSummaryVO) => {
  // 跳转到企业详情页面
  console.log('查看企业:', row.companyId)
}

/** 查看开票状态 */
const handleViewInvoiceStatus = (row: EnterpriseBillSummaryVO) => {
  // 显示开票状态详情
  console.log('查看开票状态:', row.invoiceStatus)
}

/** 查看开票信息 */
const handleViewInvoiceInfo = async (row: EnterpriseBillSummaryVO) => {
  if (!row.invoiceInfoId) {
    ElMessage.warning('该企业暂无开票信息')
    return
  }
  
  try {
    console.log('查看开票信息，ID:', row.invoiceInfoId)
    const response = await getInvoiceInfoApi(row.invoiceInfoId)
    console.log('开票信息返回数据:', response)
    // 若依框架返回的数据结构是 { code: 0, data: {...}, msg: 'success' }
    currentInvoiceInfo.value = response.data || response
    invoiceInfoDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取开票信息失败')
    console.error('获取开票信息失败:', error)
  }
}

/** 查看收款信息 */
const handleViewCollectionInfo = async (row: EnterpriseBillSummaryVO) => {
  if (!row.collectionInfoId) {
    ElMessage.warning('该企业暂无收款信息')
    return
  }
  
  try {
    console.log('查看收款信息，ID:', row.collectionInfoId)
    const response = await getCollectionInfoApi(row.collectionInfoId)
    console.log('收款信息返回数据:', response)
    // 若依框架返回的数据结构是 { code: 0, data: {...}, msg: 'success' }
    currentCollectionInfo.value = response.data || response
    collectionInfoDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取收款信息失败')
    console.error('获取收款信息失败:', error)
  }
}

/** 格式化金额 */
const formatMoney = (amount: number) => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(amount)
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.box-card {
  margin-bottom: 10px;
}
.dialog-footer {
  text-align: right;
}
</style> 